﻿using CSRedis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.Cache
{
    public class RedisCacheProvider : ICache
    {
        private readonly CSRedisClient _redisClient;

        public RedisCacheProvider(string redisConnectionString)
        {
            _redisClient = new CSRedisClient(redisConnectionString);
            RedisHelper.Initialization(_redisClient);
        }

        public void Set(string key, object value, TimeSpan? absoluteExpirationRelativeToNow = null)
        {
            if (absoluteExpirationRelativeToNow == null)
                _redisClient.Set(key, value);
            else
                _redisClient.Set(key, value, absoluteExpirationRelativeToNow.Value);
        }

        public T Get<T>(string key)
        {
            return _redisClient.Get<T>(key);
        }

        public void Remove(string key)
        {
            _redisClient.Del(key);
        }

        public IDictionary<string, string> GetAll()
        {
            var keys = _redisClient.Keys("*");  // 获取所有缓存键
            var cacheItems = new Dictionary<string, string>();

            foreach (var key in keys)
            {
                var value = _redisClient.Get(key);
                cacheItems.Add(key, value);
            }

            return cacheItems;
        }

        public bool Exists(string key)
        {
            return _redisClient.Exists(key); // 判断键是否存在
        }

        public void Clear()
        {
            var prefix = RedisHelper.Prefix;
            var keys = _redisClient.Keys($"{prefix}*");  // 获取所有缓存键
            if (keys == null || keys.Length != 0) return;
            var rawKeys = keys
                     .Select(k => k.StartsWith(prefix) ? k[prefix.Length..] : k)
                     .ToArray();
            _redisClient.Del(keys);  // 删除所有键
        }

        public void RemoveByPattern(string keyPattern)
        {
            var prefix = RedisHelper.Prefix;
            // 1. 手动带上前缀去查所有匹配的 key
            var realPattern = $"{prefix}{keyPattern}";
            var keysWithPrefix = _redisClient.Keys(realPattern);
            if (keysWithPrefix == null || keysWithPrefix.Length == 0) return;

            // 2. 剥离前缀，得到原始 key 名称
            var rawKeys = keysWithPrefix
                .Select(k => k.StartsWith(prefix) ? k[prefix.Length..] : k)
                .ToArray();

            _redisClient.Del(rawKeys);
        }
    }

}
